<template>
  <view class="profile-container">
    <uni-nav-bar left-icon="back" @clickLeft="goBack" title="个人资料" />
    
    <!-- 头像区域 -->
    <view class="avatar-section">
      <view class="avatar-wrapper">
        <image class="avatar" :src="userInfo.picture || '/static/home_user.png'" @click="chooseAvatar"></image>
        <view class="avatar-tip">点击更换头像</view>
      </view>
    </view>
    
    <!-- 信息表单区域 -->
    <view class="form-section">
      <view class="form-item">
        <text class="label">账号名</text>
        <input class="input" v-model="userInfo.accountName" placeholder="请输入账号名" />
      </view>
      
      <view class="form-item">
        <text class="label">手机号</text>
        <text class="value">{{userInfo.phone || '未绑定'}}</text>
      </view>
      
      <button class="save-btn" @click="saveProfile">保存修改</button>
    </view>
  </view>
</template>

<script>
import request from '@/util/request.js';

export default {
  data() {
    return {
      userInfo: {
        accountName: '',
        phone: '',
        picture: ''
      }
    };
  },
  onLoad() {
    this.getUserInfo();
  },
  onShow() {
    this.getUserInfo(); // 每次显示页面时重新获取用户信息，确保头像更新
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    async getUserInfo() {
      try {
        const res = await request({
          url: 'property-server/getUserInfo',
          method: 'GET'
        });
        
        if (res.code === 200) {
          this.userInfo = res.data;
        }
      } catch (error) {
        console.error('获取用户信息错误:', error);
      }
    },
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          
          // 先预览选择的图片
          this.userInfo.picture = tempFilePath;
          
          // 上传图片
          this.uploadAvatar(tempFilePath);
        }
      });
    },
    uploadAvatar(filePath) {
      uni.showLoading({
        title: '上传中',
        mask: true
      });
      
      uni.uploadFile({
        url: request.baseUrl + 'property-server/uploadAvatar',
        filePath: filePath,
        name: 'file',
        header: {
          'token': uni.getStorageSync('token')
        },
        formData: {
          'phone': this.userInfo.phone  // 添加手机号作为额外参数
        },
        success: (uploadRes) => {
          const result = JSON.parse(uploadRes.data);
          
          if (result.code === 200) {
            this.userInfo.picture = result.data;
            uni.showToast({
              title: '头像上传成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '头像上传失败',
              icon: 'none'
            });
            // 恢复原头像
            this.getUserInfo();
          }
        },
        fail: () => {
          uni.showToast({
            title: '头像上传失败',
            icon: 'none'
          });
          // 恢复原头像
          this.getUserInfo();
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },
    async saveProfile() {
      if (!this.userInfo.accountName.trim()) {
        uni.showToast({
          title: '账号名不能为空',
          icon: 'none'
        });
        return;
      }
      
      try {
        uni.showLoading({
          title: '保存中',
          mask: true
        });
        
        const res = await request({
          url: 'property-server/updateUserInfo',
          method: 'POST',
          data: { 
            accountName: this.userInfo.accountName,
            phone: this.userInfo.phone
          }
        });
        
        if (res.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          // 更新上一页数据
          const pages = getCurrentPages();
          if (pages.length >= 2) {
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.$vm) {
              prevPage.$vm.getUserInfo();
            }
          }
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.msg || '保存失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('保存个人资料错误:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  }
}
</script>

<style scoped>
.profile-container {
  background: #f5f6fa;
  min-height: 100vh;
  padding-top: 88rpx;
}
.avatar-section {
  background: #fff;
  padding: 40rpx 0;
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
}
.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  border: 4rpx solid #f0f0f0;
  background: #fff;
}
.avatar-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}
.form-section {
  background: #fff;
  padding: 0 30rpx;
}
.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #f0f0f0;
}
.form-item:last-child {
  border-bottom: none;
}
.label {
  width: 160rpx;
  font-size: 28rpx;
  color: #333;
}
.input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
}
.value {
  flex: 1;
  font-size: 28rpx;
  color: #666;
}
.save-btn {
  margin: 60rpx 0;
  background: linear-gradient(90deg, #5b9df9 0%, #6ad1f9 100%);
  color: #fff;
  border-radius: 40rpx;
  font-size: 32rpx;
}
</style> 